﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace Tnelab.Wpf
{
	public partial class WindowEx
	{
		public static readonly DependencyProperty IsCloseButtonProperty =
			DependencyProperty.RegisterAttached("IsCloseButton", typeof(bool), typeof(WindowEx), new(false, OnIsCloseButtonChanged));
		static void OnIsCloseButtonChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
		{

			var CloseButtonElement = obj as UIElement;
			if (e.NewValue != e.OldValue)
			{
				var value = (bool)e.NewValue;
				if (value)
				{
					CloseButtonElement.PreviewMouseLeftButtonUp += CloseButtonElement_MouseLeftButtonUp;
				}
				else
				{
					CloseButtonElement.PreviewMouseLeftButtonUp -= CloseButtonElement_MouseLeftButtonUp;
				}
			}
		}

		private static void CloseButtonElement_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
		{
			var window = Window.GetWindow(sender as DependencyObject);
			window.Close();
		}

		public static bool GetIsCloseButton(UIElement dpo)
		{
			return (bool)dpo.GetValue(IsCloseButtonProperty);
		}

		public static void SetIsCloseButton(UIElement dpo, bool value)
		{
			dpo.SetValue(IsCloseButtonProperty, value);
		}
	}
}
